import subprocess, logging, os
from MinecraftAPIFetcher import (
    download_version_manifest,
    download_version_meta,
    download_version_client,
    download_version_libraries,
    get_version_libraries,
    get_version_client_jar
)

def launch_minecraft(version, game_data_path='./gameData'):
    """
    Launches Minecraft with the specified version.

    Args:
        version (str): The Minecraft version to launch.
    """
    try:
        # Make sure the necessary data is cached
        download_version_manifest()
        download_version_meta(version)
        download_version_client(version)
        download_version_libraries(version)

        # Get the absolute file paths to the required libraries
        libraries_paths = get_version_libraries(version)

        # Get the absolute path to the main JAR file
        main_jar_path = get_version_client_jar(version)

        # Construct the classpath for the Java command
        if os.name == 'nt':
            classpath = ";".join(libraries_paths + [main_jar_path])
        else:
            classpath = ":".join(libraries_paths + [main_jar_path])

        # Specify the Java command to launch Minecraft
        java_command = [
            "java",
            "-Xmx2G",  # Adjust the value based on your system's available memory
            "-cp",
            classpath,
            "-Dminecraft.client.jar=" + main_jar_path,
            "net.minecraft.client.main.Main",
            "--accessToken",
            "your_access_token_here",
            "--version",
            version,
            "--gameDir",
            game_data_path
        ]

        logging.info(f'Executing Java with the following arguments: {java_command}')

        # Run the Java command using subprocess
        subprocess.run(java_command)

    except Exception as e:
        logging.error(f"An error occurred: {e}")

if __name__ == "__main__":
    launch_minecraft('1.16.5')
